const inquirer = require('inquirer')

function isNull(notnull) {
  return notnull ? 'NOT NULL' : ''
}

/**
 * 字段处理
 * @param {*} fieldObj
 */
function handleField(field, fieldObj) {
  const type = fieldObj[field].type
  const nullStr = isNull(fieldObj[field].notnull)
  if (type === 'uuid') {
    return `${field} uuid ${nullStr}`
  } else if (type === 'text') {
    return `${field} text COLLATE pg_catalog."default" ${nullStr}`
  } else if (type === 'int4') {
    return `${field} integer ${nullStr} DEFAULT 1`
  }
}
// 主键描述
function handlePrimaryKey(tablename, field, fieldObj) {
  const isPrimary = fieldObj[field].isPrimary
  if (isPrimary) {
    return `CONSTRAINT ${tablename.toLocaleLowerCase()}_pkey PRIMARY KEY (${field})`
  }
  return ''
}

/**
 * 建表sql
 * @param {*} tablename 表名
 * @param {*} fields 字段对象
 */
function createSql(tablename, fields) {
  let str = `
  CREATE TABLE public.${tablename.toLocaleLowerCase()}
  (
    `
  let idx1 = 0
  // 字段描述
  for (let field in fields) {
    const value = handleField(field, fields)
    str += (idx1 !== 0 && value ? ',\n\t' : '') + value
    idx1++
  }
  let idx2 = 0
  // 主键描述
  for (let field in fields) {
    const value = handlePrimaryKey(tablename, field, fields)
    str += (value ? ',\n\t' : '') + value
    idx2++
  }
  str += `
  )
  WITH (
      OIDS = FALSE
  )
  TABLESPACE pg_default;
  
  ALTER TABLE public.${tablename.toLocaleLowerCase()}
      OWNER to postgres;`
  return str
}
let createTableTimer = null
/**
 * 建表
 * @param {*} sqlList
 * @param {*} idx
 */
function createTable(sqlList, idx, client) {
  if (idx >= sqlList.length) {
    console.log('全部创建完成')
    client.end()
    return
  }
  client.query(sqlList[idx]).then(() => {
    idx++
    clearTimeout(createTableTimer)
    createTableTimer = setTimeout(() => {
      createTable(sqlList, idx, client)
    }, 500)
  }).catch(err => {
    console.info(err)
  })
}

// 拿到所有的建表sql
function getAllCreateTableSql(list, models) {
  return new Promise((resolve, reject) => {
    const result = []
    list.forEach((name) => {
      const temp = new models[name]()
      const sql = createSql(name, temp.fields)
      result.push(sql)
    })
    resolve(result)
  })
}

function buildTable(tableInfo, models, client) {
  const currentModelList = Object.keys(models)
  const currentTableList = Object.keys(tableInfo)
  inquirer
    .prompt([
      {
        type: 'checkbox', // list列表 checkbox复选框
        name: 'type',
        message: '请选择要操作的model,按空格选择,按回车确定选择.',
        choices: [
          ...currentModelList
            .filter((item) => {
              const idx = currentTableList.indexOf(item)
              return idx === -1
            })
            .map((item) => {
              return {
                name: item
              }
            })
        ]
      }
    ])
    .then((res) => {
      const list = res.type
      getAllCreateTableSql(list, models).then((sqlList) => {
        createTable(sqlList, 0, client)
      })
    })
}
module.exports = buildTable
